package com.zqc.filter;

import com.alibaba.fastjson.JSON;
import com.zqc.common.R;
import com.zqc.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 拦截所有请求资源
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    // 路径匹配处理，支持通配符
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 1 获取请求路径
        String uri = request.getRequestURI();
        // 定义不需要处理的资源
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/upload",
                "/common/download",
                "/user/sendMsg",
                "/user/login",
//                配置swagger放行路径
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        // 2 判断请求路径是否是 登录界请求 是放行
        boolean flag = check(urls, uri);
        if (flag) {
            filterChain.doFilter(request, response);
            return;
        }

        // 3 判断后台员工是否已经登录
        Long employeeId = (Long) request.getSession().getAttribute("employee");
        if (employeeId != null) {
            // 利用ThreadLocal的工具类将登录的员工id保存到ThreadLocal中，方便统一设置更新、插入者的字段
            BaseContext.setCurrentId(employeeId);
            filterChain.doFilter(request, response);
            return;
        }

        // 3 判断前台用户是否已经登录
        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId != null) {
            // 利用ThreadLocal的工具类将登录的员工id保存到ThreadLocal中，方便统一设置更新、插入者的字段
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }

        // 如果未登录，将未登录结果返回，前端进行登录页面的跳转
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 校验访问路径是否需要处理，true 不需要， false 需要
     *
     * @param urls
     * @param uri
     * @return
     */
    private boolean check(String[] urls, String uri) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, uri);
            if (match) {
                return true;
            }
        }
        return false;
    }


}
